package com.ftdigital.primemovers_operators.fragment;


import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.ftdigital.primemovers_operators.MainActivity;
import com.ftdigital.primemovers_operators.MyApplication;
import com.ftdigital.primemovers_operators.R;
import com.ftdigital.primemovers_operators.config.GlobalData;
import com.ftdigital.primemovers_operators.config.RequestAddr;
import com.ftdigital.primemovers_operators.model.AddOilHistory;
import com.ftdigital.primemovers_operators.model.BaseModel;
import com.ftdigital.primemovers_operators.model.UserInfo;
import com.ftdigital.primemovers_operators.util.http.AjaxCallBack;
import com.ftdigital.primemovers_operators.util.http.AjaxParams;
import com.ftdigital.primemovers_operators.util.view.RoundImageView;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.squareup.picasso.Picasso;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.ViewsById;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

/**
 * 个人信息
 */
@EFragment(R.layout.fragment_edit_user_info)
public class EditUserInfoFragment extends BaseFragment {


    @ViewById(R.id.back_btn)
    ImageButton backBtn;

    @ViewById(R.id.toptitle_title)
    TextView topTitle;

    @ViewById(R.id.right_btn)
    TextView saveBtn;

    @ViewById(R.id.privateCenter_username_content)
    EditText username;
    @ViewById(R.id.privateCenter_mobile_content)
    EditText mobile;

    @ViewById(R.id.headimg)
    RoundImageView headimg;

    @ViewsById({R.id.privateCenter_station_content, R.id.privateCenter_teamname_content})
    List<TextView> detailList;

    @AfterViews
    @Override
    void initView() {
        topTitle.setText(getResources().getString(R.string.title_userinfo));
        saveBtn.setVisibility(View.VISIBLE);

        Log.i(GlobalData.TAG, "getUrl："+ MyApplication.userInfo.getData().getUrl());
        Picasso.with(getActivity()).load(MyApplication.userInfo.getData().getUrl())
                .error(R.drawable.user_headimg).resize(50, 50).into(headimg);
        username.setText(MyApplication.userInfo.getData().getUser_name());
        mobile.setText(MyApplication.userInfo.getData().getMobile());
        detailList.get(0).setText(MyApplication.userInfo.getData().getGasstation_name());
        detailList.get(1).setText(MyApplication.userInfo.getData().getEmp_no());

    }

    @Click({R.id.back_btn, R.id.right_btn, R.id.chang_head_btn})
    @Override
    void Click(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                MainActivity.getInstance().getSupportFragmentManager().popBackStack();
                break;
            case R.id.right_btn:
                submitPic();
//                Toast.makeText(getActivity(), "保存 ", Toast.LENGTH_SHORT).show();
                break;
            case R.id.chang_head_btn:
                showPickDialog();
                break;
        }

    }

    /**
     * 选择提示对话框
     */
    private void showPickDialog() {
        new AlertDialog.Builder(getActivity())
                .setTitle("设置头像...")
                .setNegativeButton("相册", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Intent intent = new Intent(Intent.ACTION_PICK, null);

                        /**
                         * 下面这句话，与其它方式写是一样的效果，如果：
                         * intent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                         * intent.setType(""image/*");设置数据类型
                         * 如果朋友们要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
                         * 这个地方小马有个疑问，希望高手解答下：就是这个数据URI与类型为什么要分两种形式来写呀？有什么区别？
                         */
                        intent.setDataAndType(
                                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                "image/*");
                        startActivityForResult(intent, 1);

                    }
                })
                .setPositiveButton("拍照", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.dismiss();
                        /**
                         * 下面这句还是老样子，调用快速拍照功能，至于为什么叫快速拍照，大家可以参考如下官方
                         * 文档，you_sdk_path/docs/guide/topics/media/camera.html
                         * 我刚看的时候因为太长就认真看，其实是错的，这个里面有用的太多了，所以大家不要认为
                         * 官方文档太长了就不看了，其实是错的，这个地方小马也错了，必须改正
                         */
                        Intent intent = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        // 下面这句指定调用相机拍照后的照片存储的路径
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                                .fromFile(new File(Environment
                                        .getExternalStorageDirectory()
                                        + "/Youin/upload",
                                        "headImg.jpg")));
                        startActivityForResult(intent, 2);
                    }
                }).show();

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            // 如果是直接从相册获取
            case 1:
                startPhotoZoom(data.getData());
                break;
            // 如果是调用相机拍照时
            case 2:
                File temp = new File(Environment.getExternalStorageDirectory()
                        + "/Youin/upload/headImg.jpg");
                startPhotoZoom(Uri.fromFile(temp));
                break;
            // 取得裁剪后的图片
            case 3:
                /**
                 * 非空判断大家一定要验证，如果不验证的话，
                 * 在剪裁之后如果发现不满意，要重新裁剪，丢弃
                 * 当前功能时，会报NullException，小马只
                 * 在这个地方加下，大家可以根据不同情况在合适的
                 * 地方做判断处理类似情况
                 *
                 */
                if (data != null) {
                    setPicToView(data);
                }
                break;
            default:
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        /*
         * 至于下面这个Intent的ACTION是怎么知道的，大家可以看下自己路径下的如下网页
         * yourself_sdk_path/docs/reference/android/content/Intent.html
         * 直接在里面Ctrl+F搜：CROP ，之前小马没仔细看过，其实安卓系统早已经有自带图片裁剪功能,
         * 是直接调本地库的，小马不懂C C++  这个不做详细了解去了，有轮子就用轮子，不再研究轮子是怎么
         * 制做的了...吼吼
         */
        Intent intent = new Intent("com.android.camera.action.CROP");
        imagePath = getPath(getActivity(), uri);


        intent.setDataAndType(uri, "image/*");
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(photo);
            headimg.setImageDrawable(drawable);
//            submitPic(picdata);
        }
    }

    String imagePath = "";

    private void submitPic() {
        AjaxParams params = new AjaxParams();
        if (!imagePath.equals("")) {
            requestUrl = RequestAddr.uploadUserInfo;
            try {
                params.put("file", new File(imagePath));
                params.put("mobile", mobile.getText().toString().trim());
                params.put("name", username.getText().toString().trim());
                params.put("user_id", MyApplication.userInfo.getData().getUser_id() + "");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            requestUrl = RequestAddr.uploadUserInfoNoPic;
            params.put("mobile", mobile.getText().toString().trim());
            params.put("name", username.getText().toString().trim());
            params.put("user_id", MyApplication.userInfo.getData().getUser_id() + "");
        }

        xtHttp.post(requestUrl, params, new AjaxCallBack() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                dealPicData(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    private void dealPicData(Object object) {
        try {
            MyApplication.userInfo = gson.fromJson(object.toString(), UserInfo.class);
        } catch (JsonSyntaxException e) {
            baseModel = gson.fromJson(object.toString(), BaseModel.class);
            return;
        }
        Toast.makeText(getActivity(), "保存成功", Toast.LENGTH_SHORT).show();
        MainActivity.getInstance().getSupportFragmentManager().popBackStack();
    }


    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }
}
